package com.java.common;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.RandomStringUtils;
/**
 * <p>临时文件上传工具</p>
 *
 * 
 * @author $Author: qingfang.wu$
 * @version $Revision:1.0 ${Date}:Jun 29, 2011 8:51:50 AM $
 */
public abstract class FileStorage {
	
	//生成随机文件名->/upload/2013/4/21/20130421084518a0a0a.jpg
	private final static SimpleDateFormat DEFAULT_DATE_FILE = new SimpleDateFormat("yyyy/MM/dd/yyyyMMddHHmmssSS");
	
	//上传根目录
	public static String getRootPath(){
		String url = FileStorage.class.getResource("/").getPath().replaceAll("%20", " ");  
	    String path = url.substring(0, url.indexOf("WEB-INF"));
		return path;
	}
	
	//图片相对路径
	protected abstract String getBasePath();
				
	/**
	 * 读取文件内容
	 */
	public FileInputStream read(String path) throws FileNotFoundException{
//		return new FileInputStream(getRootPath() + getBasePath() + path);
		return new FileInputStream(getRootPath() + path);
	}
	
	/**
	 * 读取文件内容
	 */
	public File getFile(String path){
//		return new File(getRootPath() + getBasePath() + path);
		return new File(getRootPath() + path);
	}
	/**
	 * 判断文件是否存在
	 */
	public boolean exist(String path){
//		return new File(getRootPath() + getBasePath() + path).exists();
		return new File(getRootPath() + path).exists();
	}
	
	public String getUploadFileName(String fileName){
		String name = DEFAULT_DATE_FILE.format(new Date())
		+RandomStringUtils.randomAlphabetic(5)+'.'
		+FilenameUtils.getExtension(fileName.toLowerCase());
		return name;
	}
	
	/**
	 * 保存上传文件
	 * @param inStream 上传文件流
	 * @param rootPath 上传web根目录,通过servlet获取(request.getSession().getServletContext().getRealPath("/");)
	 * @param fileName 上传原文件名，用于识别后缀名
	 */
	public String upload(InputStream inStream,String fileName){
		//构造上传文件名
		String name = getBasePath() + getUploadFileName(fileName);		
		//
		File dest = new File(getRootPath() + name);
//		System.out.println(dest.getAbsolutePath());
		if(!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
				
		OutputStream opStream = null;
		try{
			opStream = new BufferedOutputStream(new FileOutputStream(dest));			
			byte[] buffer =new byte[1024];
			int n = 0;
			while ((n = inStream.read(buffer)) != -1){
				opStream.write(buffer,0,n);
				opStream.flush();
			}			
		} catch (IOException e) {
			return null;
		}finally{
			if(inStream !=null){
				try{
					inStream.close();
				}catch (IOException e) {}
			}
			if(opStream !=null){
				try{
					opStream.close();
				}catch (IOException e) {}
			}
		}
		return name;
	}
		
	public String copy(File srcFile) throws IOException {
		String outpath= getBasePath() + getUploadFileName(srcFile.getName());
		File dest = new File(getRootPath() + outpath);
		if(!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		FileUtils.copyFile(srcFile, dest);	
		return outpath;
	}
	
	public String upload(File f) throws IOException{
		String name= getBasePath() +getUploadFileName(f.getName());
		return upload(f,name);
	}
	
	public String upload(File f,String outpath) throws IOException{
		File dest = new File(getRootPath() + outpath);
		if(!dest.getParentFile().exists())
			dest.getParentFile().mkdirs();
		FileUtils.copyFile(f, dest);
		return outpath;
	}
		
	/**
	 * 根据文件相对路径删除文件
	 */
	public void delete(String path) throws IOException{
		File desc = new File(getRootPath() + path);
		FileUtils.forceDelete(desc);
	}
}
